package com.smartlink.app.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.smartlink.app.R;
import com.smartlink.app.activity.BluetoothActivity;
import com.smartlink.app.common.Constant;
import com.smartlink.app.dialog.WaitDialog;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TeachFragment extends Fragment implements View.OnClickListener {

    private TextView tv_teach_studentNumber;
    private TextView tv_teach_real_studentNumber;
    private TextView tv_teach_lack_studentNubmer;
    private Spinner sp_teach_lack_studentName;
    private Button btn_teach_inform_sign;
    private SharedPreferences sharedPreferences;
    private TextView tv_teach_className;
    private WaitDialog waitDialog;
    private Button btn_teach_refresh;
    private boolean havaClassRoomId;
    private String classRoomId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sharedPreferences = getActivity().getSharedPreferences("main", Context.MODE_PRIVATE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_teach, container, false);
        btn_teach_refresh = (Button) view.findViewById(R.id.btn_teach_refresh);
        tv_teach_className = (TextView) view.findViewById(R.id.tv_teach_className);
        tv_teach_studentNumber = (TextView) view.findViewById(R.id.tv_teach_studentNumber);
        tv_teach_real_studentNumber = (TextView) view.findViewById(R.id.tv_teach_real_studentNumber);
        tv_teach_lack_studentNubmer = (TextView) view.findViewById(R.id.tv_teach_lack_studentNubmer);
        sp_teach_lack_studentName = (Spinner) view.findViewById(R.id.sp_teach_lack_studentName);
        btn_teach_inform_sign = (Button) view.findViewById(R.id.btn_teach_inform_sign);
        btn_teach_inform_sign.setOnClickListener(this);
        btn_teach_refresh.setOnClickListener(this);
        checkClassRoomId();
        return view;

    }

    @Override
    public void onResume() {
        if (havaClassRoomId) {
            getSignInInfo();
        } else {
            tv_teach_className.setText("无法获取所在教室");
            btn_teach_inform_sign.setEnabled(false);
            btn_teach_refresh.setEnabled(false);
        }
        super.onResume();
    }

    //初始化界面
    public void initView(int totalNumber, int realNumber, int lackNubmer, Set<String> lackName) {
        String className = sharedPreferences.getString("classRoomName", "");
        String[] names = new String[lackName.size()];
        int i = 0;
        for (String name : lackName) {
            names[i] = name;
            i++;
        }

        //初始化班级名称
        tv_teach_className.setText(className);
        btn_teach_inform_sign.setEnabled(true);
        btn_teach_refresh.setEnabled(true);

        //初始化班级总人数
        tv_teach_studentNumber.setText(totalNumber + "");

        //初始化实到人数

        tv_teach_real_studentNumber.setText(realNumber + "");
        //初始化缺勤人数
        tv_teach_lack_studentNubmer.setText(lackNubmer + "");
        //初始化缺勤姓名
        sp_teach_lack_studentName.setAdapter(new ArrayAdapter<String>(getActivity(), R.layout.item_lack_name, names));
        //加载完成，取消加载对话框
        waitDialog.dismiss();

    }

    /**
     * 教师获取教室学生签到信息
     */
    public void getSignInInfo() {
        //显示加载对话框
        waitDialog = WaitDialog.getWaitDialog(getContext());
        String classroomId = sharedPreferences.getString("classRoomId", "");
        String ip = sharedPreferences.getString("ip", Constant.HTTP.HTTP_PORT);
        String path = " http://" + ip + ":8080/smartlink/getSignInInfo?classroomId=" + classroomId;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                String body = new String(bytes);
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    String total = jsonObject.getString("total");
                    String signInNumber = jsonObject.getString("signInNumber");
                    JSONArray students = jsonObject.getJSONArray("noSiginInfo");
                    Set<String> studentsName = new HashSet<String>();
                    for (int index = 0; index < students.length(); index++) {
                        String studentName = (String) ((JSONArray) students.get(index)).get(0);
                        studentsName.add(studentName);

                    }
                    int totalNubmer = Integer.parseInt(total);
                    int realNumber = Integer.parseInt(signInNumber);
                    int lackNubmer = totalNubmer - realNumber;
                    initView(totalNubmer, realNumber, lackNubmer, studentsName);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_teach_refresh:
                getSignInInfo();
                break;
        }
    }

    /**
     * 判断是否存在教室Id
     */
    private void checkClassRoomId() {
        //判断是否有教室ID
        classRoomId = sharedPreferences.getString("classRoomId", "");
        if (classRoomId.equals("")) {
            Intent intent = new Intent(getContext(), BluetoothActivity.class);
            startActivityForResult(intent, 0x111);
        } else {
            havaClassRoomId = true;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x111) {
            if (resultCode == BluetoothActivity.RESULT_SUCCESS) {
                havaClassRoomId = true;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
